package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    // 事务注解
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {
        // 实例化实体类
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);

        // 向菜品表添加一条数据
        dishMapper.insert(dish);

        // 获取Insert生成的主键值(id)
        Long dishId = dish.getId();

        // 向口味表添加N条数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors != null && flavors.size() > 0){
            for(DishFlavor flavor : flavors){
                flavor.setDishId(dishId);
            }
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 菜品分页查询
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        // 设置分页查插件
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        Page<DishVO> dishVOS=dishMapper.pageQuery(dishPageQueryDTO);
        dishVOS.forEach(dishVO -> {
            Long categoryId = dishVO.getCategoryId();
            Category category= categoryMapper.getById(categoryId);
            dishVO.setCategoryName(category.getName());
        });
        PageResult pageResult = new PageResult(dishVOS.getTotal(),dishVOS.getResult());
        return pageResult;
    }

    /**
     * 菜品批量删除过程
     * @param ids
     */
    @Override
    @Transactional
    public void deleteBatch(List<Long> ids) {
        // 当前菜品是否能删除(起售中的菜品无法删除)
        for(Long id : ids){
            Dish dish=dishMapper.getById(id);
            if(dish.getStatus() == StatusConstant.ENABLE){
                // 当前菜品起售中
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        // 当前菜品是否能删除(被套餐关联的菜品无法删除)
        List<Long> setmealIds=setmealDishMapper.getSetmealIdsByDishIds(ids);
        if(setmealIds != null && setmealIds.size() > 0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        // 删除菜品数据
//        for(Long id : ids){
//            dishMapper.deleteById(id);
//            // 删除关联的口味数据
//            dishFlavorMapper.deleteByDishId(id);
//        }

        // 删除菜品数据
        dishMapper.deleteByIds(ids);
        // 删除关联的口味数据
        dishFlavorMapper.deleteByIds(ids);

    }

    /**
     * 根据ID查询菜品和口味数据
     * @param id
     * @return
     */
    @Override
    @Transactional
    public DishVO getByIdWithFlavor(Long id) {
        // 菜品数据
        Dish dish=dishMapper.getById(id);
        // 口味数据
        List<DishFlavor> flavor=dishFlavorMapper.getByDishId(id);
        // 封装
        DishVO dishVO=new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(flavor);

        return dishVO;
    }

    /**
     * 修改菜品数据和关联的口味数据
     * @param dishDTO
     */
    @Override
    @Transactional
    public void updateWithFlavor(DishDTO dishDTO) {
        Dish dish=new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        // 修改菜品数据
        dishMapper.update(dish);
        // 修改口味数据
            // 删除当前关联的口味数据
        dishFlavorMapper.deleteByDishId(dishDTO.getId());
            // 插入口味数据
        List<DishFlavor> flavors=dishDTO.getFlavors();
        if(flavors != null && flavors.size() > 0){
            for(DishFlavor flavor : flavors){
                flavor.setDishId(dishDTO.getId());
            }
            dishFlavorMapper.insertBatch(flavors);
        }

    }

    @Override
    public void startOrStop(Integer status,Long id) {
        Dish dish=Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.update(dish);

        // 如果是停售操作还需要将包含当前菜品的套餐停售
        if(status==StatusConstant.DISABLE){
            List<Long> dishIds=new ArrayList<>();
            dishIds.add(id);
            // 获取套餐ID
            List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(dishIds);
            if(setmealIds != null && setmealIds.size() > 0){
                for (Long setmealId : setmealIds) {
                    Setmeal setmeal=Setmeal.builder()
                            .id(setmealId)
                            .status(StatusConstant.DISABLE)
                            .build();
                    setmealMapper.update(setmeal);
                }

            }
        }
    }

    @Override
    public List<Dish> list(Long categoryId) {
        List<Dish> dishes=dishMapper.getByCategoryId(categoryId,StatusConstant.ENABLE);
        return dishes;
    }

    /**
     * 条件查询菜品和口味
     * @param categoryId
     * @return
     */
    public List<DishVO> listWithFlavor(long categoryId) {
        List<Dish> dishList = dishMapper.getByCategoryId(categoryId,StatusConstant.ENABLE);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
